﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Castle.ActiveRecord;
using System.Configuration;
using System.Collections;

namespace UHUDAL
{
    public class DALBase<T> : ActiveRecordBase
    {
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(DALBase<T>));
        private int modelCache = Convert.ToInt32(ConfigurationManager.AppSettings["CacheTime"]);
        private ISession session = ActiveRecordHelper.GetSession(typeof(DALBase<T>));
        private int result = 0;
        private IList<T> resultListGeneric = null;
        private IList resultList = null;
        private ICriteria criteria = null;
        private string name = typeof(T).ToString();
        
        //构造方法
        public DALBase()
        {}
        
        #region Categories_descriptionDAL 成员方法
        
	    //增加一条数据
        public virtual int Create(T entity)
        {
            try
            {
                CreateAndFlush(entity);
                result = 1;
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name+"\r\n----------------------------------------Create(T entity)错误日志--------------------------------------------\r\n"+ex.Message);
            }
            return result;
        }

	    //根据主键删除一条数据
        public virtual int Delete(object id)
        {
            T entity = GetModel(id);
            try
            {
                DeleteAndFlush(entity);
                result = 1;
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name+"\r\n----------------------------------------Delete(object id)错误日志--------------------------------------------\r\n" + ex.Message);
            }
            return result;
        }
        
	    //根据对象删除一条数据
        public virtual int Delete(T entity)
        {
            try
            {
                DeleteAndFlush(entity);
                result = 1;
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name+"\r\n----------------------------------------Delete(T entity)错误日志--------------------------------------------\r\n" + ex.Message);
            }
            return result;
        }

	    //更新一条数据
        public virtual int Update(T entity)
        {
            try
            {
                UpdateAndFlush(entity);
                result = 1;
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name+"\r\n----------------------------------------Update(T entity)错误日志--------------------------------------------\r\n" + ex.Message);
            }
            return result;
        }

	    //得到一个对象实体
        public virtual T GetModel(object id)
        {
            T entity = default(T);
            try
            {
                entity = (T)FindByPrimaryKey(typeof(T), id, false);
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetModel(object id)错误日志---------------------------------------------\r\n" + ex.Message);
            }
            return entity;
        }

        public virtual IList<T> GetAllList()
        {
            resultListGeneric = new List<T>();
            criteria = session.CreateCriteria(typeof(T));
            return  criteria.List<T>();
        }

	    //获得前几行数据(Hql)
        public virtual IList<T> GetTopList(int top, string where, string order)
        {
            resultListGeneric = new List<T>();
            StringBuilder hql = new StringBuilder();
            hql.Append("from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            if (!string.IsNullOrEmpty(order.Trim()))
            {
                hql.Append(" order by " + order);
            }
            try
            {
                resultListGeneric = session.CreateQuery(hql.ToString()).SetFirstResult(0).SetMaxResults(top).List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetTopList(int top, string where, string order)错误日志-------------------------------------------------\r\n" + ex.Message+"\r\n Hql==>" + hql.ToString()+"\r\n");
            }
            return resultListGeneric;
        }
        
        
        //获得前几行数据(Criteria)
        public virtual IList<T> GetTopList(int top, ICriterion criterion, Order order)
        {
            resultListGeneric = new List<T>();
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion).AddOrder(order).SetMaxResults(top);
                resultListGeneric = criteria.List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetTopList(int top, ICriterion criterion, Order order)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n");
            }
            return resultListGeneric;
        }

	    //获得数据列表(Hql)
        public virtual IList<T> GetList(string where)
        {
            resultListGeneric = new List<T>();
            StringBuilder hql = new StringBuilder();
            hql.Append("from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            try
            {
                resultListGeneric=session.CreateQuery(hql.ToString()).List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(string where)错误日志-------------------------------------------------\r\n" + ex.Message+"\r\n Hql==>" + hql.ToString()+"\r\n");
            }
            return resultListGeneric;
        }
        
        //获得数据列表(Criteria)
        public virtual IList<T> GetList(ICriterion criterion)
        {
            resultListGeneric = new List<T>();
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion);
                resultListGeneric = criteria.List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(ICriterion criterion)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n");
            }
            return resultListGeneric;
        }

	    //分页获取数据列表(Hql)
        public virtual IList<T> GetList(int pageSize, int pageIndex, string where)
        {
            resultListGeneric = new List<T>();
            int firstResult = (pageIndex - 1) * pageSize;
            StringBuilder hql = new StringBuilder();
            hql.Append("from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            try
            {
                resultListGeneric = session.CreateQuery(hql.ToString()).SetFirstResult(firstResult).SetMaxResults(pageSize).List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(int pageSize, int pageIndex, string where)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString()+"\r\n");
            }
            return resultListGeneric;
        }
        
        //分页获取数据列表(Criteria)
        public virtual IList<T> GetList(int pageSize, int pageIndex, ICriterion criterion)
        {
            resultListGeneric = new List<T>();
            int firstResult = (pageIndex - 1) * pageSize;
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion).SetFirstResult(firstResult).SetMaxResults(pageSize);
                resultListGeneric = criteria.List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(int pageSize, int pageIndex, ICriterion criterion)错误日志--------------------------------------------------\r\n" + ex.Message + "\r\n");
            }
            return resultListGeneric;
        }

	    //排序分页获取数据列表(Hql)
        public virtual IList<T> GetList(int pageSize, int pageIndex, string where, string order)
        {
            resultListGeneric = new List<T>();
            int firstResult = (pageIndex - 1) * pageSize;
            StringBuilder hql = new StringBuilder();
            hql.Append("from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            if (!string.IsNullOrEmpty(order.Trim()))
            {
                hql.Append(" order by " + order);
            }
            try
            {
                resultListGeneric = session.CreateQuery(hql.ToString()).SetFirstResult(firstResult).SetMaxResults(pageSize).List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(int pageSize, int pageIndex, string where, string order)错误日志-------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString()+"\r\n");
            }
            return resultListGeneric;
        }
        
        //根据where条件排序分页查询(设置参数)
        public virtual IList<T> GetList(int pageSize, int pageIndex, string where, string order, IDictionary<string, object> paramDictionary)
        {
            int firstResult = (pageIndex - 1) * pageSize;
            resultListGeneric = new List<T>();
            StringBuilder hql = new StringBuilder();
            hql.Append("from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            if (!string.IsNullOrEmpty(order.Trim()))
            {
                hql.Append(" order by " + order);
            }
            try
            {
                IQuery query = session.CreateQuery(hql.ToString());
                foreach (KeyValuePair<string, object> param in paramDictionary)
                {
                    //如果Parameter的Value值为Null，设置参数时，默认NHibernate为String类型
                    if (param.Value != null)
                    {
                        query.SetParameter(param.Key, param.Value);
                    }
                    else
                    {
                        query.SetParameter(param.Key, param.Value, NHibernateUtil.String);
                    }
                }
                resultListGeneric = query.SetFirstResult(firstResult).SetMaxResults(pageSize).List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name + "\r\n----------------------------------------GetList(int pageSize, int pageIndex, string where, string order, IDictionary<string, object> paramDictionary)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString() + "\r\n");
                throw ex;
            }
            return resultListGeneric;
        }
        
        //排序分页获取数据列表(Criteria)
        public virtual IList<T> GetList(int pageSize, int pageIndex, ICriterion criterion, Order order)
        {
            resultListGeneric = new List<T>();
            int firstResult = (pageIndex - 1) * pageSize;
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion).AddOrder(order).SetFirstResult(firstResult).SetMaxResults(pageSize);
                resultListGeneric = criteria.List<T>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetList(int pageSize, int pageIndex, ICriterion criterion, Order order)错误日志-----------------------------------------------------\r\n" + ex.Message + "\r\n");
            }
            return resultListGeneric;
        }
        
        //自定义Hql语句查询
        public virtual IList GetListByHql(int pageSize, int pageIndex, string hql)
        {
            int firstResult = (pageIndex - 1) * pageSize;
            resultList = new ArrayList();
            try
            {
                resultList = session.CreateQuery(hql).SetFirstResult(firstResult).SetMaxResults(pageSize).List();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetListByHql(int pageSize, int pageIndex, string hql)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString() + "\r\n");
            }
            return resultList;
        }

        //自定义Sql语句查询
        public virtual IList GetListBySql(int pageSize, int pageIndex, string sql)
        {
            int firstResult = (pageIndex - 1) * pageSize;
            resultList = new ArrayList();
            try
            {
                resultList = session.CreateSQLQuery(sql).SetFirstResult(firstResult).SetMaxResults(pageSize).List();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetListBySql(int pageSize, int pageIndex, string sql)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Sql==>" + sql.ToString() + "\r\n");
            }
            return resultList;
        }

        //自定义Sql语句查询
        public virtual IList GetListBySql(string sql)
        {
            resultList = new ArrayList();
            try
            {
                resultList = session.CreateSQLQuery(sql).List();
            }
            catch (Exception ex)
            {
                log.Error(name + "\r\n----------------------------------------GetListBySql(int pageSize, int pageIndex, string sql)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Sql==>" + sql.ToString() + "\r\n");
            }
            return resultList;
        }

        /// <summary>
        /// 自定义Sql取总数 sql只能为 select count(1) from ..............
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual int GetCountBySQL(string sql)
        {
            int count = 0;
            IList ilist = GetListBySql(1, 1, sql);

            if (ilist.Count > 0)
            {
                count = Convert.ToInt32(ilist[0]);
            }

            return count;
        }
        
        //自定义Hql语句查询(设置参数)
        public virtual IList GetListByHql(int pageSize, int pageIndex, string hql, IDictionary<string, object> paramDictionary)
        {
            int firstResult = (pageIndex - 1) * pageSize;
            resultList = new ArrayList();
            try
            {
                IQuery query = session.CreateQuery(hql);
                foreach (KeyValuePair<string, object> param in paramDictionary)
                {
                    //如果Parameter的Value值为Null，设置参数时，默认NHibernate为String类型
                    if (param.Value != null)
                    {
                        query.SetParameter(param.Key, param.Value);
                    }
                    else
                    {
                        query.SetParameter(param.Key, param.Value, NHibernateUtil.String);
                    }
                }
                resultList = query.SetFirstResult(firstResult).SetMaxResults(pageSize).List();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetListByHql(int pageSize, int pageIndex, string hql, IDictionary<string, object> paramDictionary)错误日志------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString() + "\r\n");
                throw ex;
            }
            return resultList;
        }
        
        //自定义Sql语句查询(设置参数)
        public virtual IList GetListBySql(int pageSize, int pageIndex, string sql, IDictionary<string, object> paramDictionary)
        {
            int firstResult = (pageIndex - 1) * pageSize;
            resultList = new ArrayList();
            try
            {
                IQuery query = session.CreateSQLQuery(sql);
                foreach (KeyValuePair<string, object> param in paramDictionary)
                {
                    //如果Parameter的Value值为Null，设置参数时，默认NHibernate为String类型
                    if (param.Value != null)
                    {
                        query.SetParameter(param.Key, param.Value);
                    }
                    else
                    {
                        query.SetParameter(param.Key, param.Value, NHibernateUtil.String);
                    }
                }
                resultList = query.SetFirstResult(firstResult).SetMaxResults(pageSize).List();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetListBySql(int pageSize, int pageIndex, string sql, IDictionary<string, object> paramDictionary)错误日志----------------------------------------------\r\n" + ex.Message + "\r\n Sql==>" + sql.ToString() + "\r\n");
                throw ex;
            }
            return resultList;
        }

        //自定义Sql语句查询(设置参数)
        public virtual IList GetListBySql(string sql, IDictionary<string, object> paramDictionary)
        {
            resultList = new ArrayList();
            try
            {
                IQuery query = session.CreateSQLQuery(sql);
                foreach (KeyValuePair<string, object> param in paramDictionary)
                {
                    //如果Parameter的Value值为Null，设置参数时，默认NHibernate为String类型
                    if (param.Value != null)
                    {
                        query.SetParameter(param.Key, param.Value);
                    }
                    else
                    {
                        query.SetParameter(param.Key, param.Value, NHibernateUtil.String);
                    }
                }
                resultList = query.List();
            }
            catch (Exception ex)
            {
                log.Error(name + "\r\n----------------------------------------GetListBySql(string sql, IDictionary<string, object> paramDictionary)错误日志----------------------------------------------\r\n" + ex.Message + "\r\n Sql==>" + sql.ToString() + "\r\n");
                throw ex;
            }
            return resultList;
        }

	    //根据条件取数据条数(Hql)
        public virtual int GetCount(string where)
        {
            StringBuilder hql = new StringBuilder();
            hql.Append("select count(1) from "+name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            int result = 0;
            try
            {
                IList<long> lt = session.CreateQuery(hql.ToString()).List<long>();
                return Convert.ToInt32(lt[0]);
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name+"\r\n----------------------------------------GetCount(string where)错误日志----------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString()+"\r\n");
            }
            return result;
        }
        
        //根据条件取数据条数(Hql)
        public virtual int GetCount(string where,IDictionary<string, object> paramDictionary)
        {
            StringBuilder hql = new StringBuilder();
            hql.Append("select count(1) from " + name);
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            int result = 0;
            try
            {
                IQuery query = session.CreateQuery(hql.ToString());
                foreach (KeyValuePair<string, object> param in paramDictionary)
                {
                    //如果Parameter的Value值为Null，设置参数时，默认NHibernate为String类型
                    if (param.Value != null)
                    {
                        query.SetParameter(param.Key, param.Value);
                    }
                    else
                    {
                        query.SetParameter(param.Key, param.Value, NHibernateUtil.String);
                    }
                }
                IList<long> lt = query.List<long>();
                return Convert.ToInt32(lt[0]);
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(name + "\r\n----------------------------------------GetCount(string where,IDictionary<string, object> paramDictionary)错误日志----------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString() + "\r\n");
            }
            return result;
        }
        
        //根据条件取数据条数(Criteria)
        public virtual int GetCount(ICriterion criterion)
        {
            IList<int> counts = null;
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion).SetProjection(Projections.RowCount());
                counts = criteria.List<int>();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetCount(ICriterion criterion)错误日志---------------------------------------------------\r\n" + ex.Message + "\r\n");
            }
            if (counts != null && counts.Count > 0)
            {
                return counts[0];
            }
            return 0;
        }
        
        //根据条件取数据条数(Criteria)
        public virtual double GetSum(string where, string str)
        {
            IList sums = null;
            StringBuilder hql = new StringBuilder();
            hql.Append("select sum(" + str + ") from " + name + " a");
            if (!string.IsNullOrEmpty(where.Trim()))
            {
                hql.Append(" where " + where);
            }
            try
            {
                sums = session.CreateQuery(hql.ToString()).List();
            }
            catch (Exception ex)
            {
                log.Error(name + "\r\n----------------------------------------GetSum(string where, string str)错误日志---------------------------------------------------\r\n" + ex.Message + "\r\n Hql==>" + hql.ToString() + "\r\n");
                return 0;
            }
            if (sums != null && sums.Count > 0)
            {
                return Convert.ToDouble(sums[0]);
            }
            return 0;
        }

        //根据条件取数据条数(Criteria)
        public virtual double GetSum(ICriterion criterion, string str)
        {
            IList sums = null;
            try
            {
                criteria = session.CreateCriteria(typeof(T));
                criteria.Add(criterion).SetProjection(Projections.Sum(str));
                sums = criteria.List();
            }
            catch (Exception ex)
            {
                log.Error(name+"\r\n----------------------------------------GetSum(ICriterion criterion, string str)错误日志---------------------------------------------------\r\n" + ex.Message + "\r\n");
                return 0;
            }
            if (sums != null && sums.Count > 0)
            {
                return Convert.ToDouble(sums[0]);
            }
            return 0;
        }
        
        //得到一个对象实体，从缓存中
        public virtual T GetModelByCache(object id)
        {
            string cacheKey = name + "Id-" + id;
            object objModel = Maticsoft.Common.DataCache.GetCache(cacheKey);
            if (objModel == null)
            {
                try
                {
                    objModel = GetModel(id);
                    if (objModel != null)
                    {
                        Maticsoft.Common.DataCache.SetCache(cacheKey, objModel, DateTime.Now.AddMinutes(modelCache), TimeSpan.Zero);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(name+"\r\n----------------------------------------GetModelByCache(object id)错误日志-------------------------------------\r\n" + ex.Message);
                }
            }
            return (T)objModel;
        }

        //根据Where条件从缓存中取数据列表
        public virtual IList<T> GetListByCache(string where)
        {
            string cacheKey = name + "ByWhere-" + where;
            object objList = Maticsoft.Common.DataCache.GetCache(cacheKey);
            if (objList == null)
            {
                try
                {
                    objList = GetList(where);
                    if (objList != null && ((IList<T>)objList).Count > 0)
                    {
                        Maticsoft.Common.DataCache.SetCache(cacheKey, objList, DateTime.Now.AddMinutes(modelCache), TimeSpan.Zero);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(name+"\r\n----------------------------------------GetListByCache(string where)错误日志-------------------------------------\r\n" + ex.Message);
                }
            }
            return (IList<T>)objList;
        }
        
        //根据Where条件分页从缓存中取数据列表
        public virtual IList<T> GetListByCache(int pageSize, int pageIndex, string where, string order, IDictionary<string, object> paramDictionary)
        {
            string whereString = "";
            foreach (KeyValuePair<string, object> paramKeyValuePair in paramDictionary)
            {
                whereString += where.Replace(":"+paramKeyValuePair.Key, paramKeyValuePair.Value.ToString());
            }
            string cacheKey = name + "ByWhere-" + whereString + " and PageIndex = " + pageIndex;
            object objList = Maticsoft.Common.DataCache.GetCache(cacheKey);
            if (objList == null)
            {
                try
                {
                    objList = GetList(pageSize, pageIndex, where, order, paramDictionary);
                    if (objList != null && ((IList<T>)objList).Count > 0)
                    {
                        Maticsoft.Common.DataCache.SetCache(cacheKey, objList, DateTime.Now.AddMinutes(modelCache), TimeSpan.Zero);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(name + "\r\n----------------------------------------GetListByCache(int pageSize, int pageIndex, string where, string order, IDictionary<string, object> paramDictionary)错误日志-------------------------------------\r\n" + ex.Message);
                }
            }
            return (IList<T>)objList;
        }
        #endregion


       
    }
}
